package com.example.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.common.Result;
import com.example.entity.DoctorStatus;
import com.example.entity.dto.DoctorDto;
import com.example.service.DoctorStatusService;
import com.example.entity.User;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.service.UserService;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;
import com.example.exception.CustomException;
import cn.hutool.core.util.StrUtil;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.math.BigDecimal;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/doctorStatus")
public class DoctorStatusController {
    @Resource
    private DoctorStatusService doctorStatusService;
    @Resource
    private UserService userService;
    @Resource
    private HttpServletRequest request;

    public User getUser() {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            throw new CustomException("-1", "请登录");
        }
        return user;
    }

    @PostMapping
    public Result<?> save(@RequestBody DoctorStatus doctorStatus) {
        return Result.success(doctorStatusService.save(doctorStatus));
    }

    /**
     * 修改医生转态
     * @param doctorStatus
     * @return
     */
    @PutMapping
    public Result<?> update(@RequestBody DoctorStatus doctorStatus) {
        return Result.success(doctorStatusService.saveOrUpdate(doctorStatus));
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        doctorStatusService.removeById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<?> findById(@PathVariable Long id) {
        return Result.success(doctorStatusService.getById(id));
    }

    @GetMapping
    public Result<?> findAll() {
        return Result.success(doctorStatusService.list());
    }

    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(required = false, defaultValue = "") String name,
                                                @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                                @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        //1.创建两个分页对象
        // 1.1医生基本信息 分页
        Page<User> userPage = new Page<>(pageNum, pageSize);
        // 1.2含有医生状态 分页 dto
        Page<DoctorDto> doctorDtoPage = new Page<>(pageNum, pageSize);
        //2.查询医生基本信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //2.1 姓名模糊查询
        queryWrapper.like(name!=null, User::getNickName ,name);
        //2.2 查询角色是医生
        queryWrapper.like(User::getRole,"2");
        userService.page(userPage, queryWrapper);
        //3.分页对象流处理 包含医生状态信息
        BeanUtil.copyProperties(userPage, doctorDtoPage, "records");
        List<DoctorDto> collect = userPage.getRecords().stream().map(o -> {
            DoctorDto doctorDto = new DoctorDto();
            // 复制基本信息
            BeanUtil.copyProperties(o, doctorDto);
            // 查询医生状态 根据医生id
            DoctorStatus status = doctorStatusService.getById(o.getId());
            if (status == null) {
                // 设置默认 1--在线 2--忙碌 3--离线
                doctorDto.setStatus(1);
            }else {
                doctorDto.setStatus(status.getStatus());
            }
            return doctorDto;
        }).collect(Collectors.toList());

        // 设置dto 并放回分页对象
        doctorDtoPage.setRecords(collect);
        return Result.success(doctorDtoPage);
    }

//    @GetMapping("/export")
//    public void export(HttpServletResponse response) throws IOException {
//
//        List<Map<String, Object>> list = CollUtil.newArrayList();
//
//        List<DoctorStatus> all = doctorStatusService.list();
//        for (DoctorStatus obj : all) {
//            Map<String, Object> row = new LinkedHashMap<>();
//            row.put("医生id", obj.getId());
//            row.put("", obj.getDoctorId());
//            row.put("", obj.getStatus());
//
//            list.add(row);
//        }
//
//        // 2. 写excel
//        ExcelWriter writer = ExcelUtil.getWriter(true);
//        writer.write(list, true);
//
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
//        String fileName = URLEncoder.encode("医生在线状态信息", "UTF-8");
//        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
//
//        ServletOutputStream out = response.getOutputStream();
//        writer.flush(out, true);
//        writer.close();
//        IoUtil.close(System.out);
//    }
//
//    @GetMapping("/upload/{fileId}")
//    public Result<?> upload(@PathVariable String fileId) {
//        String basePath = System.getProperty("user.dir") + "/src/main/resources/static/file/";
//        List<String> fileNames = FileUtil.listFileNames(basePath);
//        String file = fileNames.stream().filter(name -> name.contains(fileId)).findAny().orElse("");
//        List<List<Object>> lists = ExcelUtil.getReader(basePath + file).read(1);
//        List<DoctorStatus> saveList = new ArrayList<>();
//        for (List<Object> row : lists) {
//            DoctorStatus obj = new DoctorStatus();
//            obj.setStatus(Integer.valueOf((String) row.get(2)));
//
//            saveList.add(obj);
//        }
//        doctorStatusService.saveBatch(saveList);
//        return Result.success();
//    }

}
